using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;

namespace LastFMPPC
{
	class Mp3Playa
	{
		private static int instance = 0;

		#region DllImports
		
		[DllImport("mp3playa.dll")]
		private static extern int mpInit();

		[DllImport("mp3playa.dll")]
		private static extern void mpClose(int instance);

		[DllImport("mp3playa.dll")]
		private static extern int mpEnqueue(int instance, byte[] buffer, int size);

		[DllImport("mp3playa.dll")]
		private static extern int mpVolume(int instance, int volume);

		#endregion

		/// <summary>
		/// Inits the mp3playa engine.
		/// </summary>
		public static void Init()
		{
			if (instance != 0) return;

			instance = mpInit();
			if (instance == 0)
			{
				throw new LastException("Mp3Playa.Init: error in native code!");
			}
		}

		/// <summary>
		/// Closes the mp3playa engine.
		/// </summary>
		public static void Close()
		{
			try
			{
				if (instance != 0) mpClose(instance);
				instance = 0;
			}
			catch (Exception exp)
			{
				throw new LastException("Mp3Playa.Close: " + exp.Message);
			}
		}

		/// <summary>
		/// Enqueue mp3 stream for playback.
		/// </summary>
		/// <param name="buffer">The piece of stream.</param>
		public static void Enqueue(byte[] buffer, int length)
		{
			if (instance == 0) throw new LastException("Mp3playa.Enqueue: not inited!");

			if (mpEnqueue(instance, buffer, length) == 0)
			{
				throw new LastException("Mp3Playa.Enqueue: Could not enqueue stream!");
			}
		}

		/// <summary>
		/// Sets the wave output volume.
		/// </summary>
		/// <param name="volume">Volume (0-256).</param>
		public static void Volume(int volume)
		{
			if (instance == 0) return;
			try
			{
				mpVolume(instance, volume);
			}
			catch (Exception exp)
			{
				throw new LastException("Mp3Playa.Volume: " + exp.Message);
			}
		}
	}
}
